import { defineStore } from 'pinia'
//引入登录接口
import { reqLoginAPI, reqUserInfoAPI, reqLogoutAPI } from '@/apis/user'
//引入登录数据类型
import type { userState } from '@/store/modules/types/type'
import type { loginFormData, loginResponseData, userInfoResponseData } from '@/apis/user/type'
//引入本地存储封装的方法
import { setToken, getToken, removeToken } from '@/utils/token'
import constanRoute from '@/router/routes'


const useUserStore = defineStore('User', {
  //小仓库
  state: (): userState => {
    return {
      token: getToken(),
      menuRoutes: constanRoute, //菜单路由
      userName: '',
      avatar: '',
      //存储当前用户是否包含某一个按钮
      buttons: [],
    }
  },
  //异步或者逻辑的方法
  actions: {
    //登录
    async userLogin(data: loginFormData) {
      let result: loginResponseData = await reqLoginAPI(data)
      if (result.code === 200) {
        this.token = result.data as string
        setToken(result.data as string)
        return 'ok'
      } else {
        return Promise.reject(new Error(result.data))
      }
    },
    //获取用户信息
    async UserInfo() {
      const result:userInfoResponseData = await reqUserInfoAPI()
      if (result.code === 200) {
        this.userName = result.data.name
        this.avatar = result.data.avatar
      } else {
        return Promise.reject(new Error(result.message))
      }
    },
    //退出登录
    async userLogout() {
      const result:any = await reqLogoutAPI()
      if (result.code === 200) {
        this.token = null
        this.avatar = ''
        this.userName = ''
        removeToken()
        return 'ok'
      } else {
        return Promise.reject(new Error(result.message))
      }
    },
  },
  //计算属性
  getters: {},
})

export default useUserStore
